<?php
namespace intelligent\vcard\client\controllers;

use Yii;
use heihei\filters\auth\JwtAuth;
use heihei\rest\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\filters\auth\CompositeAuth;
use yii\web\ForbiddenHttpException;

/**
 * 基础控制器
 */
class BaseController extends Controller
{
    protected $allowActions = ['login'];
    
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        $behaviors = parent::behaviors();

        if(!in_array($this->action->id, $this->allowActions)){
            $behaviors['authenticator'] = [
                'class' => CompositeAuth::className(),
                'optional' => ['*'],
                'authMethods' => [
                    [
                        'class' => JwtAuth::className()
                    ]
                ],
            ];
        }
        

        $behaviors['access'] = [
            'class' => AccessControl::className(),
            'rules' => [
                [
                  'actions' => $this->allowActions,
                  'allow' => true,
                ],
                ['allow' => true,'roles' => ['@']]
            ],
        ];

        $behaviors['verbs'] = [
            'class' => VerbFilter::className(),
            'actions' => [
                //'logout' => ['post'],
            ],
        ];
        return $behaviors;
    }

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if (!parent::beforeAction($action)) {
            return false;
        }

        if ($this->checkAccess()) {
            return true;
        }

        throw new ForbiddenHttpException('不允许请求,无请求权限！');
    }

    /**
     * 检测请求当前控制器是否允许
     *
     * @return bool
     */
    public function checkAccess()
    {
        $user = Yii::$app->getUser();
        if($user->getIsGuest()){
            return true;
        }
        return $user->can($this->route);
    }
}
